package org.nobject.common.code.script;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.nobject.common.js.JSONUtils;
import org.nobject.common.lang.MapUtils;


/**
 * JavascriptUtils
 * 
 * 暂时无法用 Binding绑定复杂的变量
 * 
 * @author bianrongjun
 * @version 1.0
 */
public class JavascriptUtils {
	
	/** 
	 * execute
	 * @param exp
	 * @param $
	 * @return
	 * @throws Exception
	 */
	public static Object execute(String exp,Object $) throws Exception{
		return execute(exp, $, "$");
	}
	
	/** 
	 * execute
	 * @param exp
	 * @param $
	 * @param $Name
	 * @return
	 * @throws Exception
	 */
	public static Object execute(String exp,Object $,String $Name) throws Exception{
		ScriptEngine se = new ScriptEngineManager().getEngineByName("ECMAScript");
		CompiledScript script = ((Compilable) se).compile("var $="+JSONUtils.toString($)+";" + exp);
		return script.eval();
	}
	
	
	public static void main(String[] args) throws Exception{
		Object param=MapUtils.toMap(new Object[][]{
			{"contractFee",100}
		}) ;
		
		
		Object result=execute("$.contractFee*(0.1+1000)", param);
		
		System.out.println(result);
	}
	
}
